package com.slife.shiro;

import org.apache.shiro.SecurityUtils;

import java.lang.reflect.Field;

/**
 * Created by chen on 2017/7/28.
 * <p/>
 * Email 122741482@qq.com
 * <p/>
 * Describe: shiro 用户封装的工具类
 */
public class SlifeSysUser {
    /**
     * 取出Shiro中的当前用户LoginName.
     */
    public static String name() {
        return ShiroUser().getName();
    }

    public static String photo() {
        return ShiroUser().getPhoto();
    }

    public static Long id() {
        return ShiroUser().getId();
    }

    public static String loginName() {
        return ShiroUser().getUsername();
    }

    public static ShiroUser ShiroUser() {
        Object userObject = SecurityUtils.getSubject().getPrincipal();
        Field[] fields = userObject.getClass().getDeclaredFields();

//强转异常        return (ShiroUser) userObject;

        Long id = 0L;
        String username = "";
        String name = "";
        String photo = "";
        try {

            for (Field field : fields) {
                field.setAccessible(true);
                switch (field.getName()) {
                    case "id":
                        id = (Long) field.get(userObject);
                        break;
                    case "username":
                        username = (String) field.get(userObject);
                        break;
                    case "name":
                        name = (String) field.get(userObject);
                        break;
                    case "photo":
                        photo = (String) field.get(userObject);
                        break;
                    case "serialVersionUID":
                        break;
                    default:
                        System.err.println(userObject);
                }
            }
            return new ShiroUser(id,username,name,photo);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }

    }
}
